package com.healthysys.backend.config.db;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.healthysys.backend.mapper.UserFullInfoVOMapper;
import com.healthysys.backend.mapper.UserRoleAuthorityVOMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;
import pojo.entity.UserFullInfoVO;
import pojo.vo.UserRoleAuthorityVO;

@Component
@Slf4j
public class DBUserConfigManager implements UserDetailsManager, UserDetailsPasswordService {

    @Resource
    private UserFullInfoVOMapper userFullInfoVOMapper;

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    @Override
    public void createUser(UserDetails user) {

    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }

    /**
     * 从数据库中载入用户数据
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserFullInfoVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UserFullInfoVO user = userFullInfoVOMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return User.builder()
                .username(user.getUsername())
                .password(user.getPassword()) 
                .authorities(AuthorityUtils.createAuthorityList(user.getAuthorities()))
                .accountExpired(false)
                .credentialsExpired(false)
                .accountLocked(false)
                .disabled(false)
                .build();
    }
}
